<?php

namespace plugin\ycMassage\utils;


class Yunxin
{
    const HOST = 'http://101.37.133.245:11108';
    public $platform = 'voice';
    public $version = '1.0.0';
    public $appid = '';
    public $token = '';
    public $timestamp = '';
    public function __construct($saas_appid)
    {
        $config=getHpConfig('', (int)$saas_appid, 'winnerlook');
        if(empty($config['state'])){
            throw new \Exception('云信未开启');
        }
        if(empty($config['appid']) || empty($config['token'])){
            throw new \Exception('请配置云信appid和token');
        }
        $this->appid = $config['appid'];
        $this->token = $config['token'];
    }
    public function getAuthorization()
    {
        return base64_encode($this->appid . ':' . $this->timestamp);
    }
    public function getSig()
    {
        return md5($this->appid . $this->token . $this->timestamp);
    }
    public function getClient()
    {
        $this->timestamp = microtime(true) * 1000;
        return new \GuzzleHttp\Client([
            'base_uri' => self::HOST,
            'headers' => [
                'Authorization' => $this->getAuthorization(),
                'Content-Type' => 'application/json',
            ]
        ]);

    }
    public function middleNumberAXB($data)
    {
        $client = $this->getClient();
        $response = $client->request('POST', $this->platform . '/' . $this->version . '/middleNumberAXB/' . $this->appid . '/' . $this->getSig(), [
            'json' => $data
        ]);
        $result = $response->getBody()->getContents();
        $result = json_decode($result);
        if($result->result!='000000'){
            throw new \Exception($result->result.':'.$result->message);
        }
        return $result;
    }
    public function middleNumberUnbind($data)
    {
        $client = $this->getClient();
        $response = $client->request('POST', $this->platform . '/' . $this->version . '/middleNumberUnbind/' . $this->appid . '/' . $this->getSig(), [
            'json' => $data
        ]);
        $result = $response->getBody()->getContents();
        $result = json_decode($result);
        if($result->result!='000000'){
            throw new \Exception($result->result.':'.$result->message);
        }
        return $result;
    }
    public function notify($data)
    {
        $client = $this->getClient();
        $response = $client->request('POST', $this->platform . '/' . $this->version . '/notify/' . $this->appid . '/' . $this->getSig(), [
            'json' => $data
        ]);
        $result = $response->getBody()->getContents();
        $result = json_decode($result);
        if($result->result!='000000'){
            throw new \Exception($result->result.':'.$result->message);
        }
        return $result;
    }
}
